package org.advanced.expand;

/**
 * @author John.zhang
 * @version Id: TransAccount, v 1.0 2020/12/11 17:18 ZhiYong Exp $
 * 死锁
 */
public class TransAccount implements Runnable {

    private Account fromAccount;

    private Account toAccount;

    private int amount;

    public TransAccount(Account fromAccount, Account toAccount, int amount) {
        this.fromAccount = fromAccount;
        this.toAccount = toAccount;
        this.amount = amount;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (fromAccount) {
                synchronized (toAccount) {
                    if (fromAccount.getBalance() >= amount) {
                        fromAccount.debit(amount);
                        toAccount.credit(amount);
                    }
                }
                System.out.println(fromAccount.getAccountName()+"-"+fromAccount.getBalance());
                System.out.println(toAccount.getAccountName()+"-"+toAccount.getBalance());
            }
        }
    }


    public static void main(String[] args) {
        Account fromAccount = new Account("张三", 100000);
        Account toAccount = new Account("李四", 200000);

        //两个线程锁的先后锁的资源不同
        Thread threadA = new Thread(new TransAccount(fromAccount, toAccount, 1));
        Thread threadB = new Thread(new TransAccount(toAccount, fromAccount, 1));
        threadA.start();
        threadB.start();
    }

}
